<?php

define("BOX_ERROR", "error");
define("BOX_WARNING", "warning");
define("BOX_INFO", "info");
define("STICKER_ACTIVE", 0);
define("STICKER_INACTIVE", 1);
define("STICKER_ERROR", 2);
define("STICKER_WARNING", 3);

class page_manager {

    public $gzcompress = false;   // use compression to reduce bandwidth
    public $elements_embed = false;   // embedded elements
    public $template = null;      // template engine instance
    public $template_path = null;
    public $userid = null;
    public $logins = null;
    public $logo_image = null;
    public $page;
    public $users;
    public $session_userid;
    public $mainmenu;
    public $leftmenu;
    public $rightmenu;
    public $topmenu;
    public $submenu;
    public $webpage_name;
    public $odd;
    public $web_content;
    public $nosession = true;    // do not handle logins/sessions!

    /**
     * Assign template path
     *
     * @param string $template
     * Template instance
     * @param string $path
     * Path to web template
     * @param string $webpage_name
     * Name of the web page
     */

    public function __construct($template = NULL, $path, $webpage_name) {
        if (!$template)
            $this->template = new template;
        else
            $this->template = $template;
        $this->template_path = $path;
        $this->template->set_template_path($this->template_path);
        $this->webpage_name = $webpage_name;
    }

    /**
     * Clean string to be SQL safe
     *
     * @param string $str
     * String to be escaped
     * @param boolean $encode_ent
     * Encode or not
     * @return string
     * Escaped string
     */
    public function clean($str, $encode_ent = false) {
        $str = @trim($str);
        if ($encode_ent) {
            $str = htmlentities($str);
        }
        if (version_compare(phpversion(), '4.3.0') >= 0) {
            if (get_magic_quotes_gpc())
                $str = stripslashes($str);
            if (function_exists("mysql_real_escape_string")) {
                $str1 = mysql_real_escape_string($str);
                if (empty($str1))
                    $str = addslashes($str);
                else
                    $str = $str1;
            }
            else
                $str = addslashes($str);
        }
        else
        if (!get_magic_quotes_gpc())
            $str = addslashes($str);
        return $str;
    }

    /**
     * Create bar HTML element
     *
     * @param string $title
     * Bar title (name)
     * @param int $value
     * Bar current value (etc... 5 of 70)
     * @param int $max
     * Bar maximum value (etc.... 70)
     * @param int $width
     * Bar width as HTML size
     * @param boolean $onlyperc
     * Show only percentage
     * @return type
     */
    public function create_bar($title, $value, $max, $width = 300, $onlyperc = true) {
        $perc = ROUND(($value * 100) / $max);
        if ($perc > 100)
            $perc = 100;
        $wcell1 = ($width / 100) * $perc;
        $wcell2 = ($width / 100) * (100 - $perc);
        if ($onlyperc)
            $printval = "{$perc}%";
        else
            $printval = "{$value}({$perc}%)";
        $output.="<table border=0 cellpadding=0 cellspacing=2 frame=void ><tr><td>{$title}</td><td width={$wcell1}px style='background-color: #888888'><center><strong>{$printval}</strong></center></td><td width={$wcell2} style='background-color: #dddddd'></td></tr></table>";
        return $output;
    }

    /**
     * Create graph as image
     *
     * @param int $width
     * Image width
     * @param int $height
     * Image height
     * @param array $data
     * Image data
     * @param string $title
     * Image title
     * @param int $xaxis
     * Image x axis
     * @param int $yaxis
     * Image y axis
     * @param string $type
     * Type of the bar
     * @return string
     * Image link
     */
    public function create_graph($width = 600, $height = 200, $data, $title, $xaxis, $yaxis, $type = "bar") {
        require_once ('jpgraph/jpgraph.php');
        require_once ('jpgraph/jpgraph_line.php');
        require_once ('jpgraph/jpgraph_bar.php');
        require_once ('jpgraph/jpgraph_pie.php');

        // Create a graph instance
        if ($type == "bar" || $type == "line")
            $graph = new Graph($width, $height); else
        if ($type == "pie")
            $graph = new PieGraph($width, $height);

        // Specify what scale we want to use,
        // int = integer scale for the X-axis
        // int = integer scale for the Y-axis
        $graph->SetScale('intint');
        $graph->SetMarginColor("lightblue:1.1");
        $graph->SetShadow();
        $graph->SetMargin(60, 20, 10, 40);

        // Box around plotarea
        $graph->SetBox();

        // No frame around the image
        $graph->SetFrame(false);

        // Setup a title for the graph
        $graph->title->Set($title);
        $graph->title->SetMargin(8);
        $graph->title->SetColor("darkred");

        // Setup the X and Y grid
        $graph->ygrid->SetFill(true, '#DDDDDD@0.5', '#BBBBBB@0.5');
        $graph->ygrid->SetLineStyle('dashed');
        $graph->ygrid->SetColor('gray');
        $graph->xgrid->Show();
        $graph->xgrid->SetLineStyle('dashed');
        $graph->xgrid->SetColor('gray');

        // Setup titles and X-axis labels, if it's array, first row is title
        if (is_array($xaxis)) {
            $graph->xaxis->title->Set($xaxis[0]);
            $xaxis = array_slice($xaxis, 1, count($xaxis) - 1);
            $graph->xaxis->SetTickLabels($xaxis);
        }
        else
            $graph->xaxis->title->Set($xaxis);  // no array, just show name







// Setup Y-axis title
        $graph->yaxis->title->SetMargin(10);
        $graph->yaxis->title->Set($yaxis);

        if ($type == "bar") {
            $plot = new BarPlot($data);
            $plot->SetWidth(0.6);
            $fcol = '#440000';
            $tcol = '#FF9090';
            $plot->SetFillGradient("navy:0.9", "navy:1.85", GRAD_LEFT_REFLECTION);
            //$plot->SetColor("black");
            // Set line weigth to 0 so that there are no border
            // around each bar
            $plot->SetWeight(0);
            // Add the plot to the graph
            $graph->Add($plot);
        } else
        if ($type == "line") {
            $plot = new LinePlot($data);
            $plot->SetFillColor('skyblue@0.5');
            $plot->SetColor('navy@0.7');
            $plot->mark->SetType(MARK_SQUARE);
            $plot->mark->SetColor('blue@0.5');
            $plot->mark->SetFillColor('lightblue');
            $plot->mark->SetSize(5);
            // Add the plot to the graph
            $graph->Add($plot);
        } else
        if ($type == "pie") {
            $plot = new PiePlot($data);
            $plot->SetCenter(0.5, 0.55);
            $plot->SetSize(0.2);

            // Enable and set policy for guide-lines
            $plot->SetGuideLines();
            $plot->SetGuideLinesAdjust(1.4);

            // Setup the labels
            $plot->SetLabelType(PIE_VALUE_PER);
            $plot->value->Show();
            //$plot->value->SetFont(FF_ARIAL,FS_NORMAL,9);
            $plot->value->SetFormat('%2.1f%%');
            $plot->ExplodeSlice(1);
            $plot->SetGuideLines(true);
            $graph->SetMarginColor("white");

            $plot->SetLegends($xaxis);

            // Add the plot to the graph
            $graph->Add($plot);
        }
        else
            die($type . " is not known graph type");

        // Display the graph
        $fn = strtolower($title);
        $fn = str_replace(" ", "", $fn);
        $filename_relative = "site/web_app/images/dynamic/{$fn}.jpg";
        $filename_full = __DIR__ . "/" . $filename_relative;
        $graph->Stroke($filename_full);
        $imglink = "<img src='{$filename_relative}' title='{$title}' />\n";
        return $imglink;
    }

    /**
     * Text in title class
     *
     * @param string $text
     * Text to show
     */
    public function text_title($text) {
        $output = '<h2 class="title">' . $text . '</h2><br>' . "\n";
        $this->web_content.=$output;
    }

    /**
     * Show block message on page
     *
     * @param string $message
     * Message text
     * @param string $type
     * Message type class (error,notice,warning)
     */
    public function block_message($message, $type = "error") {
        $class = $type;
        $output = '<div class="inner">
              <div class="flash">
                <div class="message ' . $class . '">
                  <p>Error message</p>
                  </div>
                  ' . $message . '
              </div>';
        $this->web_content.=$output;
    }

    /**
     * Start form in the web page
     *
     * @param string $formid
     * Form ID
     */
    public function start_form($formid) {
        $output = "<form action=\"{$link}\" id=\"$formid\" class=\"form\" method='POST'>\n";
        $this->web_content.=$output;
    }

    /**
     * End form
     *
     */
    public function end_form() {
        $output = "</form>\n";
        $this->web_content.=$output;
    }

    /**
     * Adds a form element to the page
     *
     * @param string $element
     * Element to add to form
     */
    public function form_add_element($element) {
        $this->web_content.=$element;
    }

    /**
     * Adds field in the form
     *
     * @param string $name
     * Name of the field
     * @param string $description
     * Description of the field
     * @param string $type
     * Type of the field
     * @param string $default
     * Default value
     */
    public function form_add_field($name, $description, $fieldname, $default = "", $type = "text") {
        switch ($type) {
            case "text":
                $class = "class=\"text_field\"";
                break;
            case "checkbox":
                $class = "class=\"checkbox\"";
                break;
            case "radio":
                $class = "class=\"checkbox\"";
                break;
            default:
        }
        if ($type != "hidden")
            $output = "<label class=\"label\">{$name}</label>";
        $output.="<input type='{$type}' name='{$fieldname}' id='{$fieldname}' {$class} value='$default' /><br>\n";
        if ($description && $type != "hidden")
            $output.="<span class=\"description\">{$description}</span>";
        $this->web_content.=$output;
    }

    /**
     * Add button on the form
     *
     * @param string $name
     * Button name
     * @param string $link
     * Button link
     * @param string $img
     * Button image
     * @param string $vars
     * Predefined variables
     */
    public function form_add_button($name, $link = "#", $img = "cross.png", $vars = "") {
        $link_parts = explode("?", $link);
        if ($link_parts[1]) {
            $link_args = explode("&", $link_parts[1]);
            foreach ($link_args as $link_arg) {
                $link_arg = explode("=", $link_arg);
                $vars.="<input type='hidden' name='{$link_arg[0]}' id='{$link_arg[0]}' value='{$link_arg[1]}' />\n";
            }
        }
        if ($vars)
            $output.=$vars;
        $output.='<button class="button" type="submit" name="' . $name . '" id="' . $name . '"><img src="' . $this->template_path . 'images/icons/' . $img . '" alt="' . $name . '" /> ' . $name . '</button>' . "<br>\n";
        $this->web_content.=$output;
    }

    /**
     * Sticker text in the page
     *
     * @param type $text
     * Sticker text
     * @param type $status
     * Sticker status (STICKER_ACTIVE, STICKER_INACTIVE, STICKER_WARNING, STICKER_ERROR)
     */
    public function sticker($text, $status) {
        switch ($status) {
            case STICKER_ACTIVE:
                $boxcolor = "green";
                $textcolor = "white";
                break;
            case STICKER_INACTIVE:
                $boxcolor = "gray";
                $textcolor = "white";
                break;
            case STICKER_WARNING:
                $boxcolor = "blue";
                $textcolor = "white";
                break;
            case STICKER_ERROR:
                $boxcolor = "red";
                $textcolor = "white";
                break;
            default:
        }
        $output = "<table border-spacing: 2px><tr><td bgcolor={$boxcolor}><font size=1 color='{$textcolor}'>&nbsp{$text}&nbsp</font></td></tr></table>";
        $this->web_content.=$output;
    }

    /**
     * Show table in style
     *
     * @param array $header
     * Add header to table
     * @param array $data
     * Table data (content)
     * @param boolean $checkbox
     * Checkbox on line
     * @param string $buttons
     * Show buttons
     * @param type $viewlimit
     * ???
     * @param type $callback
     * ???
     * Callback function
     */
    public function style_table($header, $data, $checkbox, $buttons, $viewlimit, $callback) {
        foreach ($header as $hdr) {
            $title = $hdr["title"];
            $color = $hdr["color"];
            $type = $hdr["type"];
            $sum = $hdr["sum"];
            $output_header.="<th><strong><font color='{$color}'>{$title}</font></strong></th>\n";
        }
        $class = "odd";
        $id = 1;
        foreach ($data as $item) {
            $lines.="<tr class=\"{$class}\" onmouseover=\"this.clasName='odd';\" onmouseout=\"this.clasName='even';\">\n";
            if ($checkbox)
                $lines.="  <td><input type=\"checkbox\" class=\"checkbox\" name=\"id_{$item['id']}\" value=\"{$item['id']}\" /></td>\n";
            $ic = 0;

            foreach ($item as $i) {
                $color = $header[$ic]["color"];
                $sum = $header[$ic]["sum"];
                if ($sum)
                    $total_cell[$ic]+=(int) $i;
                $lines.="<td><font color='{$color}'>{$i}</font></td>";
                $ic++;
            }
            $lines.="</tr>\n";
            if ($class == "odd")
                $class = "even";
            else
                $class = "odd";
        }
        foreach ($buttons as $button) {
            $button_code.='<button class="button" type="submit" id="' . $button . '" name="' . $button . '"> ' . $button . ' </button>';
        }
        $output = <<<table
<form action="#" class="form">
                <table class="table">
                  <tr>
                  <th class="first"><input type="checkbox" class="checkbox toggle" /></th>
                    {$output_header}
                    <th class="last">&nbsp;</th>
                  </tr>
                {$lines}
                </table>
                <div class="actions-bar wat-cf">
                  <div class="actions">
                    {$button_code}
                  </div>
                </div>
              </form>
table;
        $this->web_content.=$output;
    }

//style_table

    /**
     * Display simple table
     *
     * @param array $header
     * Display header
     * @param array $data
     * Display data
     */
    public function simple_table($header, $data) {
        $output = "<table class='table'>\n";
        if (!empty($header)) {
            $output.="<tr>\n";
            foreach ($header as $row) {
                $output.="<td>{$row}</td>";
            }
            $output.="</tr>\n";
        }

        foreach ($data as $row) {
            if (!$this->odd) {
                $this->odd = true;
                $class = "odd";
            } else {
                $this->odd = false;
                $class = "even";
            }
            $output.="<tr class='{$class}'>\n";
            foreach ($row as $row1) {
                $output.="<td>{$row1}</td>";
            }
            $output.="</tr>\n";
        }
        $output.="</table>\n";
        $this->web_content.=$output;
    }

    /**
     * Add menus to page
     *
     * @param array $menus
     * Menus to add
     */
    public function menus($menus) {
        $this->mainmenu = '<ul class="wat-cf">';
        foreach ($menus as $menu => $value) {
            if ($this->page === $menu)
                $class = "active";
            else
                $class = "first";
            if (!empty($value["icon"]))
                $img_link = "<img src='{$this->template_path}/{$value["icon"]}' /><br />";
            else
                $img_link = "";
            $this->mainmenu.='<li class="' . $class . '"><a href="' . $value['link'] . '">' . $img_link . $value['name'] . '</a></li>';
        }
        $this->mainmenu.='</ul>';
    }

    /**
     * Add right menu to the page
     *
     * @param boolean $info
     * Shows info
     * @param boolean $profile
     * Show profile info
     * @param boolean $logout
     * Shows logout link
     * @return string
     */
    public function rightmenu($info = false, $profile = true, $logout = true) {
        if ($info !== false) {
            $infoline = $info;
        }
        $out = '<ul class="wat-cf">
          <li><a href="index.php?page=profile"><img src="' . $this->template_path . '/images/user.png"><br>Profile</a></li>
          <li><a class="logout" href="index.php?page=logout"><img src="' . $this->template_path . '/images/forward.png"><br>Logout</a></li>
          <li>' . $infoline . '</li>
        </ul>';
        return $out;
    }

    /**
     * Add submenu to page
     *
     * @param array $submenu
     * Submenu to add
     */
    public function submenu($submenu) {
        $this->submenu = '<div class="secondary-navigation"><ul class="wat-cf">' . "\n";
        $active_submenu = strtolower($_GET["submenu"]);
        foreach ($submenu as $menu => $value) {
            if ($active_submenu === strtolower($value["name"]))
                $class = ' class="active first"';
            else
                $class = '';
            $uri = $_SERVER["REQUEST_URI"];
            $uria = explode("&", $uri);
            $uri_base = $uria[0];
            $link = "submenu=" . $value["name"];
            $icon = $value["icon"];
            $rights = $value["rights"];
            $enabled = $value["enabled"];
            if ($icon)
                $icon = "<img width=8 height=8 src='{$this->template_path}images/{$icon}' /> ";
            else
                $icon = "";
            if ($enabled)
                $this->submenu.=' <li' . $class . '><a href="' . $uri_base . "&" . $link . '">' . $icon . $value['name'] . '</a></li>' . "\n";
            else
                $this->submenu.=' <li' . $class . '><a href="#"><font color=gray>' . $icon . $value['name'] . '</font></a></li>' . "\n";
        }
        $this->submenu.='</ul></div>' . "\n";
    }

    /**
     * Gets user session ID
     *
     * @param type $id
     * ID of the user
     * @return string
     * Returns session ID
     */
    public function getuserinfo($id) {
        if (empty($id)) {
            $id = $this->session_userid;
        }
        return $id;
    }

    /**
     * Check if user is logged in
     *
     * @param string $username
     * Username
     * @param type $password
     * Password
     * @return boolean
     * True if logged in, false if not
     */
    public function checklogin($username, $password) {
        foreach ($this->users as $user => $value) {
            if ($username === $user && $password === $value["password"]) {
                $this->session_userid = $value["id"];
                return TRUE;
            }
        }
        return FALSE;
    }

    /**
     * Manage sessions
     * Try to log in user or $func
     *
     * @param type $func
     * Can be logout, getinfo, default is to try to log in
     * @return boolean
     */
    public function session($func) {
        $username = $this->clean($_POST["username"]);
        $password = $this->clean($_POST["password"]);
        session_start();
        $this->session_userid = (int) $_SESSION['SESS_USER_ID'];
        // Log out user, delete session
        if ($func == "logout") {
            unset($_SESSION['SESS_USER_ID']);
            session_write_close();
            $this->page = "login";
            return true;
        } else
        if ($func == "getinfo") {
            return $this->session_userid;
        }

        if (!empty($username) && !empty($password)) {   // user try to login
            if ($this->checklogin($username, $password)) {   // login ok?
                //Regenerate session ID to prevent session fixation attacks
                //var_dump($this->session_userid);die;
                session_regenerate_id();
                $_SESSION['SESS_USER_ID'] = $this->session_userid;
                session_write_close();
                return true;
            } else {    // login not ok!
                $this->tags = array(
                    "formaction" => "index.php?page=index",
                    "message" => "wrong username or password!",
                    "TEMPLATE_PATH" => $this->template_path,
                );
                // Display login page
                $this->template->get_page("login");
                $this->template->set_pageexpiration(PAGE_EXPIRATION_NOW);
                $this->template->quickrender($this->tags) or die("error rendering login page");
                die();
            }
        } else
        if (empty($this->session_userid)) {    // user not logged in?
            $this->tags = array(
                "formaction" => "index.php?page=index",
                "message" => "type username and password",
                "title" => strip_tags($this->webpage_name),
                "TEMPLATE_PATH" => $this->template_path,
            );
            $this->template->get_page("login");
            $this->template->set_pageexpiration(PAGE_EXPIRATION_NOW);
            $this->template->quickrender($this->tags) or die("error rendering login page");
            die();
        }
        else
            return TRUE;    // user logged, found id
    }

    /**
     * Load page
     *
     * @param string $page
     * Page user is trying to access
     * @param array $users
     * Users array
     */
    public function load($page, $users) {
        if (!$this->nosession) {
            // Special logout page, replace with index
            if ($page == "logout") {
                $this->session("logout");
                $page = "login";
            }
            $this->page = $page;
            $this->users = $users;
            $this->session();   // check session
        }
        if (empty($page))
            $page = "index";
        $this->template->get_page("index");
    }

    /**
     * Finish page, assign tags and render
     *
     * @param string $content
     * Page content
     * @param boolean $info
     * Show info or not
     * @param boolean $profile
     * Show profile
     * @param boolean $logout
     * Show logout
     */
    public function finish_script($content, $info = false, $profile = true, $logout = true) {
        $this->tags = array(
            "mainmenu" => $this->mainmenu,
            //"rightmenu" => $this->rightmenu($info, $profile, $logout),
            "rightmenu" => "",
            "submenu" => $this->submenu,
            "title" => strip_tags($this->webpage_name) . "-" . $this->page,
            "webpage_name" => $this->webpage_name,
            "logo_image" => $this->logo_image,
            "TEMPLATE_PATH" => $this->template_path,
            "content" => $content,
        );
        $this->template->set_pageexpiration(PAGE_EXPIRATION_NOW);
        $this->template->quickrender($this->tags, $this->gzcompress, $this->elements_embed);
    }

}

?>